package org.hd.source.controller;


import org.hd.source.dto.*;
import org.hd.source.entity.Source;
import org.hd.source.exception.BizException;
import org.hd.source.service.SourceService;
import org.hd.source.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

@RestController
@RequestMapping("source")
public class SourceController {

    @Autowired
    private SourceService sourceService;

    @GetMapping("list")
    public Result getSourceList(SourceListQuery query){
        return Result.SUCCESS().setData(sourceService.getSourceListPage(query));
    }

    @PostMapping("save")
    public Result save(@RequestBody SourceDto sourceDto){
        sourceService.save(sourceDto);
        return Result.SUCCESS();
    }

    @GetMapping("info")
    public Result getSourceInfo(String sourceId){
        return Result.SUCCESS().setData(sourceService.getSource(sourceId));
    }

    @GetMapping("info-simple")
    public Result getSourceInfoSimple(String sourceId) {
        return Result.SUCCESS().setData(sourceService.getSourceSimple(sourceId));

    }

    @PostMapping("dInfos")
    public Result getDownloadInfos(@RequestBody DownloadInfoReq req){
        String token = req.getSourceAuth();
        boolean isLogin = JwtUtils.verifyToken(token);
        if(!isLogin){
            throw BizException.TOKEN_EXPIRED_ERROR;
        }
        return Result.SUCCESS().setData("list", sourceService.getDownloadInfos(req.getSourceId(), token));
    }

    @GetMapping("updateStatus")
    public Result updateStatus(String sourceId, Integer status){
        sourceService.updateStatus(sourceId, status);
        return Result.SUCCESS();
    }

    @GetMapping("simpleSourcePage")
    public Result simpleSourcePage(SourceListQuery query){
        return Result.SUCCESS().setData(sourceService.simpleSourcePage(query));
    }

    @GetMapping("recommends")
    public Result recommendSources(String tagId, String sourceId) {
        SourceListQuery query = new SourceListQuery();
        query.setTagId(tagId);
        query.setPageIndex(1);
        query.setPageSize(8);
        PageResult<Source> result = sourceService.simpleSourcePage(query);
        result.setRecords(result.getRecords().stream().filter(e -> !e.getId().equals(sourceId)).collect(Collectors.toList()));
        return Result.SUCCESS().setData(result);
    }

}
